package com.qf.commons.aop;

import com.qf.commons.annotation.UserLogin;
import com.qf.commons.utils.HttpUtils;
import com.qf.entity.Emp;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * User: key
 * ClassName:UserLoginAop
 * Date: 2023/5/30
 * Time: 18:40
 * description:
 */
@Component
@Aspect
public class UserLoginAop {
    public UserLoginAop() {
        System.out.println("看看我执行了几次");
    }
    @Around("@annotation(userLogin)")
    public Object findUserLogin(ProceedingJoinPoint point, UserLogin userLogin) throws Throwable {
        //获取当前登录用户
        Emp emp = (Emp) HttpUtils.getSession().getAttribute("loginUser");
        //判断是否必须注入
        boolean required = userLogin.required();
        if(required){
            if(emp == null){
                return "commons/login";
            }
        }
        //获取目标方法的参数
        Object[] args = point.getArgs();
        for (int i = 0; i < args.length; i++) {
            if(args[i].getClass() == Emp.class){
                args[i] = emp;
                break;
            }
        }
        //放行
        Object proceed = point.proceed(point.getArgs());
        return proceed;
    }
}
